package com.jhd.fuzhou.view.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.adapter.OrgAdapter;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.service.PDFService;
import com.jhd.fuzhou.service.SpecialService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DateTime;
import com.jhd.fuzhou.util.NavigationBarUtil;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.daily.DailyDocumentInquiryRecordActivity;
import com.jhd.fuzhou.view.daily.DailyDocumentSuperviseOpinionActivity;
import com.jhd.fuzhou.view.dossier.DossierActivity;
import com.jhd.fuzhou.view.random.DoubleDocumentInquiryRecordActivity;
import com.jhd.fuzhou.view.random.DoubleDocumentSuperviseOpinionActivity;
import com.jhd.fuzhou.view.special.SpecialDocumentInquiryRecordActivity;
import com.jhd.fuzhou.view.special.SpecialDocumentSuperviseOpinionActivity;
import com.jhd.fuzhou.vo.CheckValue;
import com.jhd.fuzhou.vo.DocumentNoClaimVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.OrganizationVo;
import com.jhd.fuzhou.vo.SearchUnit;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisedUnitVo;
import com.jhd.fuzhou.vo.SupervisionInspectionVo;
import com.jhd.fuzhou.vo.Supervisor;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public abstract class BaseActivity extends AppCompatActivity {
    protected FuzhouApplication application;
    private Stack<WeakReference<Activity>> mActivityStack;
    protected List<CheckValue> checkValue;
    protected DocumentNoClaimVo documentNoClaimVo;
    public ProgressDialog _dialog;
    public List<SupervisedUnitVo> supervisedUnitVoList=new ArrayList<>();
    public List<Supervisor> supervisorList=new ArrayList<Supervisor>();;
    private List<OrganizationVo> organizationVoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        application = (FuzhouApplication) getApplication();
        //隐藏底部虚拟按键
        NavigationBarUtil.hideNavigationBar(getWindow());
        loadViewLayout();
        ButterKnife.bind(this);
        processLogic();
    }

    protected void onBack(){
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }
    protected void updateTitle(String title){
        ((TextView)findViewById(R.id.tv_title)).setText(title);
    }


    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        //把操作放在用户点击的时候
        if (me.getAction() == MotionEvent.ACTION_DOWN) {
            //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, me)) {
                //收起键盘
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(me);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 加载布局文件
     */
    protected abstract void loadViewLayout();

    /*根据单位名称和code获取单位地址信息列表*/
    protected void getAddressByUnitIdAndCredit(Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("creditCode",supervisionInspectionVo.getCreditCode()==null?"":supervisionInspectionVo.getCreditCode())
                .addParam("name",supervisionInspectionVo.getUnitName()==null?"":supervisionInspectionVo.getUnitName());
        Call<JsonForResult> jsonForResultCall = vs.getAddressByUnitIdAndCredit(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            supervisedUnitVoList = JSON.parseArray(jsonForResult.getData().toString(), SupervisedUnitVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }

            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    //根据所属专业的Id获取专业明细列表
    //orgId=11ebdafc9f0538dead0a80bfd7c3a8ef&deptId=11ebdb00b68c38dead0a80bfbaf7159a&useSystem=1&status=1
    protected void getSupervisorSelector(Context context){
        _dialog = new ProgressDialog(context);
        _dialog.setCancelable(false);
        if(!_dialog.isShowing()){
            _dialog.setMessage("正在获取监督员列表,请稍等...");
            _dialog.show();
        }
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("joinSuperviseWork","1")
                .addParam("orgId",(application.getOrgId()==null)?"": application.getOrgId()).addParam("useSystem","1").addParam("status","1");
        Call<JsonForResult> jsonForResultCall = vs.getPersonInfoList(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()==null){
                        }else{
                            supervisorList = JSON.parseArray(jsonForResult.getData().toString(), Supervisor.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*protected String checkDocument(SupervisionInspectionVo supervisionInspectionVo,String type){
        List<SuperviseEnclosureVo> superviseEnclosureVoList = supervisionInspectionVo.getCheckDocumentNo();
        if(superviseEnclosureVoList!=null){
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                if(type.equals(superviseEnclosureVo.getEnclosureName())){
                    if(!StringUtil.isNullOrEmpty(superviseEnclosureVo.getDocumentNo())){
                        return superviseEnclosureVo.getDocumentNo();
                    }
                }
            }
        }
        return null;
    }*/
    protected String checkDocument(SupervisionInspectionVo supervisionInspectionVo,String type){
        SuperviseEnclosureVo superviseEnclosureVo = supervisionInspectionVo.getDocumentNo();
        if(superviseEnclosureVo!=null){
            if(!StringUtil.isNullOrEmpty(superviseEnclosureVo.getDocumentNo())){
                return superviseEnclosureVo.getDocumentNo();
            }
        }
        return null;
    }
    /*获取文书编号*/
    protected void takeDocumentNo(SupervisionInspectionVo supervisionInspectionVo, Button button,Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("claimDeptId",(application.getDeptId()==null)?"":application.getDeptId());
        params.put("docType","日常监督文书");
        if(supervisionInspectionVo.getDocumentNo()!=null)params.put("documentNo",supervisionInspectionVo.getDocumentNo().getDocumentNo().substring(5));
        Call<JsonForResult> jsonForResultCall = vs.takeDocumentNo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){

                        }else{
                            if(jsonForResult.getMessage()!=null){
                                //CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                            }
                        }
                    }else if(jsonForResult!=null&&!jsonForResult.isSuccess()&&jsonForResult.getMessage()!=null){
                        CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                    }
                } catch (Exception e) {
                    button.setEnabled(true);
                    CustomToast.showText(context,e.getMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                String msg = "获取文书编号失败!";
                CustomToast.showText(context, "获取文书编号失败!",3000,0,0).show();
                button.setEnabled(true);
            }
        });
    }

    protected void takeDocumentNo2(SupervisionInspectionVo supervisionInspectionVo, String type,Button button, String fileUrl ,int newClass, Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("claimDeptId",(application.getDeptId()==null)?"":application.getDeptId());
        params.put("docType","日常监督文书");
        Call<JsonForResult> jsonForResultCall = vs.takeDocumentNo(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    button.setEnabled(true);
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            documentNoClaimVo= JSON.parseObject(jsonForResult.getData().toString(), DocumentNoClaimVo.class);
                            String documentNo=DateTime.getYear()+"-"+String.valueOf(documentNoClaimVo.getCurrentNo());
                            Intent intent = null;
                            if(newClass==1){
                                intent=new Intent(context, DailyDocumentInquiryRecordActivity.class);
                            }else if(newClass==2){
                                intent=new Intent(context, DailyDocumentSuperviseOpinionActivity.class);
                            }else if(newClass==3){
                                intent=new Intent(context, DoubleDocumentInquiryRecordActivity.class);
                            }else if(newClass==4){
                                intent=new Intent(context, DoubleDocumentSuperviseOpinionActivity.class);
                            }else if(newClass==5){
                                intent=new Intent(context, SpecialDocumentInquiryRecordActivity.class);
                            }else if(newClass==6){
                                intent=new Intent(context, SpecialDocumentSuperviseOpinionActivity.class);
                            }
                            intent.putExtra("fileUrl",fileUrl);
                            intent.putExtra("type",type);
                            intent.putExtra("documentNo",documentNo);
                            startActivity(intent);
                            UploadFile.saveDocNo(supervisionInspectionVo,DateTime.getYear()+"-"+String.valueOf(documentNoClaimVo.getCurrentNo()),type);
                        }else{
                            if(jsonForResult.getMessage()!=null){
                                CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                            }
                        }
                    }else if(jsonForResult!=null&&!jsonForResult.isSuccess()&&jsonForResult.getMessage()!=null){
                        CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getMessage(),3000,0,0).show();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                button.setEnabled(true);
                String msg = "获取文书编号失败!";
                CustomToast.showText(context, "获取文书编号失败!",3000,0,0).show();
            }
        });
    }
    /**
     * 加载业务数据
     */
    protected abstract void processLogic();
    protected void getCheckValue(JSONArray jsonArray){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("nameList",jsonArray);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
                JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.getValueList(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            checkValue= JSON.parseArray(jsonForResult.getData().toString(), CheckValue.class);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(getApplicationContext(), "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取检测项目失败!";
                UtilHelper.alertMsg(getApplicationContext(), "错误", msg);
            }
        });
    }
    //获取获取监管机构
    protected void getOrgSelector(Context context){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Call<JsonForResult> jsonForResultCall = vs.getOrgSelector(application.getAccessToken());//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        organizationVoList = JSON.parseArray(jsonForResult.getData().toString(), OrganizationVo.class);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public void setSuperviseDeptButton(Context context,RecyclerView recyclerView, SearchUnit searchUnit,FuzhouApplication application){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        if(organizationVoList !=null){
            OrgAdapter recyclerAdapter=new OrgAdapter(organizationVoList,searchUnit,application,context);
            recyclerView.setAdapter(recyclerAdapter);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(_dialog!=null)_dialog.dismiss();
    }
}
